<template>
  <div class="schedule-process-container">
    <a-spin :spinning="loading">
      <div class="operate-page-content">
        <a-row class="make-info-details">
          <a-col :span="3">
            <MakeInfoDetails  ref="makeInfoDetails" :scheduleInfo="scheduleInfo" :stationList="stationList" :personList="personList" />
          </a-col>
          <a-col :span="21" class="table-box pt-20 ">
            <ProcessList ref="processList" :dataList="scheduleInfo" :isView="isView" :urlType="urlType"/>
          </a-col>
        </a-row>
      </div>
      <div class="operate-page-btns" >

        <a-space v-if="isView">
          <a-button @click="closeTab" class="cancel">{{$t('common.cancel')}}</a-button>
          <a-button @click="handleOk" type="primary" class="confirm">{{ $t('other.generateRoad') }}</a-button>
        </a-space>
        <a-space v-else>
          <a-button @click="returnBack" class="cancel">{{ $t('other.back') }}</a-button>
        </a-space>
      </div>
      <LoadingDiag ref="loadingDiagRef" @ok="okLoading" />

    </a-spin>
  </div>
</template>
<script >
import MakeInfoDetails from './newModules/makeInfoDetails.vue'
import ProcessList from './newModules/processList.vue'
import LoadingDiag from './newModules/loadingDiag.vue'
import axios from '@/utils/request'
import {cloneDeep, isEmpty, pick, uniqBy} from 'lodash'
import {message} from "ant-design-vue";
import { store } from '@/store'
import {  computed} from 'vue'
// import { useRoute, useRouter } from 'vue-router'
export default {
  name: 'scheduleProcess',
  components: {
    MakeInfoDetails,
    ProcessList,
    LoadingDiag,
  },
  data () {
    return {
      loading: false,
      lineList: [],
      staffList: [],
      stationList: [],
      personList: [],
      scheduleInfo: {},
      isView: false,
      processList: {},
      dataList: {},
      timer: 1,
      timerMethod: "",
      urlType: "ie",
      tabs:computed(() => {
        return store.state.setting.tabs
      }),
    }
  },
  methods: {
    async closeTab1 (isSuccess) {
      // console.log(isSuccess)
      const tabList = cloneDeep(this.tabs)
      let changeTabs = tabList.filter((i) => {
        if (isSuccess) {
          return !['/makeManage/scheduleProcess/edit', this.$router.path].includes(i.path)
        } else {
          return i.path !== this.$router.path
        }
      })
      await store.commit('updateState', { tabs: changeTabs })
    },
    async closeTab (isSuccess) {
      const tabList = cloneDeep(this.tabs)
      let changeTabs = tabList.filter((i) => {
        if (isSuccess) {
          return !['/makeManage/scheduleProcess/edit', this.$router.path].includes(i.path)
        } else {
          return i.path !== this.$router.path
        }
      })
      await store.commit('updateState', { tabs: changeTabs })
      this.$router.replace('/makeManage/autoScheduleOnline')
    },
    async returnBack (isSuccess) {
      const tabList = cloneDeep(this.tabs)
      let changeTabs = !isEmpty(tabList) && tabList.filter((i) => {
        if (isSuccess) {
          return !['/makeManage/scheduleProcess/details', this.$router.path].includes(i.path)
        } else {
          return i.path !== this.$router.path
        }
      })
      await store.commit('updateState', { tabs: changeTabs })

      if (this.$route.query.type == 'sch'){
        this.$router.replace('/makeManage/autoScheduleLocal')
      }else if(this.$route.query.type == 'loc'){
        this.$router.replace('/makeManage/autoSchLocal')
      } else if(this.$route.query.type == 'ie') {
        this.$router.replace('/makeManage/autoScheduleOnline')
      }else{
        this.$router.back
      }
    },
    async handleOk () {
      try {
        // 删除工序不生效 使用dataSource 替换   需要优化
        let editProcessList = cloneDeep(this.$refs.processList.dataList)
        let processOnly = cloneDeep(this.$refs.processList.dataSource)
        // 非空校验    +  唯一校验
        if (processOnly){
          let isNull = false
          let isO = false
          // let uniqueValue = false
          processOnly.forEach(item=>{
            if (!item.sortField || !item.processNo || !item.name || !item.processCode|| !item.professionId || !item.standardSeconds  ){
              isNull = true
            }
            if (!item.standardSeconds ){
              isO = true
            }
          })
          //唯一值校验
          let isUniq = ['sortField','processNo','name','processCode'].some(i=>uniqBy(processOnly,i).length != processOnly.length )
          if (isUniq){
            message.warning(this.$t('other.ruleSchProcessOnly'))
            return
          }
          if (isO){
            message.warning(this.$t('other.standardTimeNotBe'))
            return
          }
          if (isNull){
            message.warning(this.$t('other.ruleSchProcessStandardTimeOnly'))
            return
          }

        }
        // console.log(processOnly,'---------------------------')
        if (editProcessList.ieRoadmapProcVO.id && editProcessList.ieRoadmapProcVO){
          editProcessList.ieRoadmapProcVO.detailList = processOnly
        }
        if (editProcessList.ieRoadmapProcVO.id && editProcessList.ieRoadmapProcVO.detailList){
          editProcessList.ieRoadmapProcVO.detailList.forEach(item=>{
            item.processId = editProcessList.ieRoadmapProcVO.id
          })
        }
        localStorage.setItem('editProcessList', JSON.stringify(editProcessList))
        // console.log(editProcessList,'editProcessList+++++++++++++++++++****************************--------------------')
        this.$refs.loadingDiagRef.open(true)
        let res = await axios.postAction('/api/mo/ie-roadmap/production-scheduling',editProcessList)
        if (res.success){
          localStorage.setItem('ieCreateRoadMapData', JSON.stringify(res.data))
          // console.log(res.data,'ieCreateRoadMapData++++++++++++++++++++++++')
          this.closeTab1(true)
          this.$router.push({
            path: '/makeManage/scheduleRoute/edit',
            query: { id: this.scheduleInfo.id}
          })
        }
        this.$refs.loadingDiagRef.open(false)
      }catch (err){
        this.$refs.loadingDiagRef.open(false)
        console.log(err)
      }
    },
    okLoading(){
      // console.log('okLoading------------')
    },

    async getMoInfo(schId){
      let res = {}
      if (this.$route.query.type == 'loc'){
        // 本地查看
        res = await axios.getAction('/api/mo/auto-roadmap/get',{id:schId})
      }else{
        res = await axios.getAction('/api/mo/ie-roadmap/get',{id:schId})
      }
      // console.log(schId,res,'------------------------------')
      if (res.success){
        let returnedTarget = {}
        const resMo = await axios.getAction('/api/mo/mo/get', {id:res.data.moId} )
        if (resMo.success){
          let params = pick(resMo.data, ['moNo', 'styleNo', 'productType', 'quantity', 'createTime'])
          returnedTarget = Object.assign(res.data, params);
          // console.log(returnedTarget,'---------------')
        }
        let staffList1 = cloneDeep(this.staffList)
        staffList1 && staffList1.forEach(item=>{
          if (res.data.staffIds.includes(item.id)){
            this.personList.push( {title:item.staffNo+'-'+item.nickName,key:item.id})
          }
        })
        let lineNo = ''
        let lineList1 = cloneDeep(this.lineList)
        lineList1 && lineList1.forEach(item=>{
          if (item.id===res.data.lineId){
            lineNo = item.lineNo
          }
        })
        returnedTarget.lineNo = lineNo

        res.data.stationNos && res.data.stationNos.forEach(item=>{
          this.stationList.push({title:lineNo+'-'+item,key:item})
        })

        let fileListName = []
        if (res.data.urlList){
          res.data.urlList && res.data.urlList.forEach((item,index)=>{
            fileListName.push(
                {
                  uid:index+1,
                  name: item.split('/').slice(-1)[0],
                  status: 'done',
                  url:item,
                  thumbUrl:item
                }
            )
          })
        }
        returnedTarget.fileListName = fileListName

        let stationNosNum = null;
        if (res.data.stationNos){
          stationNosNum = res.data.stationNos.length
        }
        returnedTarget.stationNosNum = stationNosNum
        this.scheduleInfo = returnedTarget;
        this.loading = false
      }
    },
    async initMethods(){
      let resLine = await axios.postAction('/api/device/hanger-line/list')
      if (resLine.success){  this.lineList = resLine.data; }
      const resStaff = await axios.postAction('/api/basic/staff/list')
      if (resStaff.success) this.staffList = resStaff.data
      this.isView = this.$route.path == '/makeManage/scheduleProcess/edit'? true : false
    }
  },

  async created() {
    this.loading = true
    const id = this.$route.query.id
    this.urlType = this.$route.query.type == 'loc'?'loc':'ie'
    if (id){
      await  this.initMethods()
      await this.getMoInfo(id)
    }
    try {
      // const resStaff = await axios.postAction('/api/basic/staff/list')
      // if (resStaff.success) staffList.value = resStaff.data
      // const resGroup = await axios.postAction('/api/basic/staff-group/list')
      // if (resGroup.success) staffGroupList.value = resGroup.data

      // let resLine = await axios.postAction('/api/device/hanger-line/list')
      // if (resLine.success){  lineList.value = resLine.data; }

    }catch (err){
      console.log(err)
    }

  }
}
</script>
